package cn.green.config;

import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 放csrf攻击
 */
public class CsrfSecurityRequestMatcher implements RequestMatcher {
    //正则表达式：请求方式
    private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");

    /**
     * 重写匹配机制
     * @param httpServletRequest        请求处理
     * @return                          是否匹配
     */
    @Override
    public boolean matches(HttpServletRequest httpServletRequest) {
        List<String> urls = new ArrayList<>();
        //urls.add("/api/test");//（不允许post请求的url路径）此处根据自己的需求做相应的逻辑处理
        if (urls != null && urls.size() > 0) {
            String servletPath = httpServletRequest.getServletPath();
            httpServletRequest.getParameter("");
            for (String url : urls) {
                if (servletPath.contains(url)) {
                    return true;
                }
            }
        }
        boolean matches = allowedMethods.matcher(httpServletRequest.getMethod()).matches();
       // return true;
        return matches;
    }
}
